
var utilsmd5 = require('../../utils/md5.js')
var app = getApp()
Page({
  data: {
    footer: {
      i_home: "../images/button1.png",
      i_tel: "../images/button2.png",
      i_chat: "../images/button4on.png",
      i_add: "../images/button5.png",
    },
    arraydetail: [],
    productsInfo: '',
    productsPayInfo: '',
    info: {},
    deliveryFee: 0,
    addressId: 0,
    myProduct: [],
    buttonconfirm: true,
    buttonbuy: false,
    selectall: false,
    paybase: 0,
    payall: 0,
    farmId: 0,
    aDelivery: [],
    aAddress: [],
    deliveryType: 1,
    haveDeliveryType: 0,
    userNote: '',
    haveproduct: false,
    winWidth: 0,
    winHeight: 0,
    author: 'Lotus'
  },
  buy: function () {
    var that = this;
    //var keyword = e.detail.value;  
    //console.log('form发生了submit事件，携带数据为：',e.detail.value);
    console.log(1000);
    console.log(that);
    console.log(that.data.productsInfo);
    //进行整理数据
    var myProduct = that.data.myProduct;
    var arraydetail = that.data.arraydetail;
    var goodsid = [];
    var totle = [];
    var marketprice = [];
    for (var i in myProduct) {
      goodsid[i] = that.data.myProduct[i].goodsid;
      totle[i] = that.data.myProduct[i].total;
    }

    var price = that.data.paybase;
    var address_id = that.data.aAddress.id;
    var expenses = that.data.aDelivery;
    var openid = app.globalData.openId;
    //将获取的数据进行提交到后台
    app.util.request({
      method: 'POST',
      url: 'entry/wxapp/Addorder',
      data: { openid: openid, expenses: expenses, address_id: address_id, marketprice: marketprice, price: price, totle: totle, goodsid: goodsid },
      header: { 'Content-Type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        console.log("支付")
        console.log(res);
        if (res.data.data.status == 1) {
          console.log(res);
          var orderid = res.data.data.orderid;
          var ip = '122.235.163.41';
          console.log(orderid);
          console.log('11111111111111111111111111111111111');
          app.util.request({
            method: 'POST',
            'url': 'entry/wxapp/getprepayid&orderid=' + orderid,
            data: { openid: openid, orderid: orderid, ip: ip },
            header: { 'Content-Type': 'application/x-www-form-urlencoded' },
            success: function (res) {
              console.log('11111111111111111111111111111111111');
              console.log(res);
              //进行支付
              wx.requestPayment({
                'timeStamp': res.data.data.timeStamp,
                'nonceStr': res.data.data.nonceStr,
                'package': res.data.data.package,
                'signType': 'MD5',
                'paySign': res.data.data.paySign,
                'success': function (res) {
                  //支付成功后的业务逻辑，进行
                  app.util.request({
                    method: 'POST',
                    'url': 'entry/wxapp/changeorder&orderid=' + orderid,
                    data: { orderid: orderid },
                    header: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    success: function (res) {
                      console.log('000000');
                      console.log(res);
                       console.log('请求成功');
                      console.log(orderid);
                      //状态更改成功的情况下
                        wx.navigateTo({
                          url: 'orderlist'
                        })
                    },
                    //失败的业务逻辑
                    'fail': function (res) {
                        console.log('请求失败');
                      wx.navigateTo({
                        url: 'orderlist'
                      })
                    }
                  })

                },
                'fail': function (res) {
                }
              })


            }, fail: function (res) {
              console.log('请求失败');
            },
          })
        }
      },
      fail: function (res) {
        console.log('请求失败');
      },
    })
  },

  pay: function (param) {
    var that = this;
    console.log("支付 start");
    console.log(param)
    var appid = app.globalData.APPID;
    var timeStamp = '' + param.timeStamp;
    var nonceStr = param.nonceStr;
    var pkg = param.package;
    var signType = 'MD5';
    // var key = app.globalData.KEY;
    // var paySign = utilsmd5.hexMD5('appId=' + appid + '&nonceStr=' + nonceStr + '&package=' + pkg + '&signType=' + signType + '&timeStamp=' + timeStamp + '&key=' + key).toUpperCase();
    var paySign = param.paySign;
    wx.requestPayment({
      timeStamp: timeStamp,
      nonceStr: nonceStr,
      package: pkg,
      signType: signType,
      paySign: paySign,
      success: function (res) {
        // success
        console.log("支付")
        //console.log(res)
        wx.redirectTo({
          url: 'orderlist'
        })
      },
      fail: function (res) {
        // fail
        console.log("支付失败")
        console.log(res)
      },
      complete: function () {
        // complete

        that.setData({
          buttonconfirm: true,
          buttonbuy: false
        })
        wx.redirectTo({
          url: 'orderlist'
        })
      }
    })
    console.log("支付 end");
  },
  getinfo: function () {
    var that = this;
    console.log(that);
    var productsInfo = that.data.productsInfo;
    var paybase = that.data.paybase;
    //进行设置运费，固定值
    var aDelivery = [10];
    //var info = res.data.data.info;
    var payall = (parseFloat(that.data.paybase) + parseFloat

      (aDelivery)).toFixed(2);



    that.setData({

      aDelivery: aDelivery,
      payall: payall,
      buttonconfirm: false,
      buttonbuy: true
    })







  },
  setinfo: function () {
    var that = this;
    console.log("setinfo");

    var farmId = that.data.farmId;
    var products = that.data.arraydetail;
    var myProduct = that.data.myProduct;
    var deliveryType = that.data.deliveryType;
    var deliveryFee = that.data.deliveryFee;
    var userNote = that.data.userNote;
    var no = 0;
    var paybase = 0;
    console.log(products);
    var productsInfo = '{"' + farmId + '":[';
    var productsPayInfo = '{"' + farmId + '":{"couponId":0,"deliveryType":"' + deliveryType + '","deliveryFee":"' + deliveryFee + '","userNote":"' + userNote + '","items":[';
    for (var i in products) {
      if (myProduct[products[i].goodsid]) {
        if (no > 0) {
          productsInfo += ',';
          productsPayInfo += ',';
        }
        productsInfo += '{"productId":' + products[i].goodsid + ',"buyAmount":' + products[i].total + '}';
        productsPayInfo += '{"productId":' + products[i].goodsid + ',"buyAmount":' + products[i].total + '}';
        paybase += products[i].total * products[i].goods_info.marketprice;
        no++;
      }
    }
    productsInfo += ']}';
    productsPayInfo += ']}}';

    that.setData({ productsPayInfo: productsPayInfo, productsInfo: productsInfo, paybase: paybase, buttonconfirm: true, buttonbuy: false })
  },
  getlist: function () {
    var that = this;
    var openid = app.globalData.openId;
    app.util.request({
      'url': 'entry/wxapp/Getcart' + '&openid=' + openid,
      'cachetime': '30',
      success: function (res) {
        //console.log("success:" + res.data.data.code);



        var arraydetail = res.data.data;
        var haveproduct = true;
        that.setData({
          arraydetail: arraydetail,
          haveproduct: haveproduct,

        })


      },
      fail: function (res) {
        console.log("fail:" + res);
      },
    })
  },
  /* getlist: function () {
     var that = this;
     var goods_id = this.data.goods_id;
     var openid = app.globalData.openId;
     var haveproduct = false;
     wx.request({
       method: 'POST',
       'url': 'entry/wxapp/Getcart&openid=' + openid,
 
       header: { 'Content-Type': 'application/x-www-form-urlencoded' },
       success: function (res) {
         //console.log("success:" + res.data.data.code);
         console.log(10);
         if (!res.data.data.code) {
           var list = res.data.data.list;
           var products = res.data.data.list[0].products;
           var farmId = res.data.data.list[0].farmId;
           haveproduct = true;
           that.setData({
             arraydetail: res.data.data.list[0].products,
             haveproduct: haveproduct,
             farmId: farmId
           })
         }
         if (res.data.data.code == '1') {
           that.setData({
             arraydetail: [],
             haveproduct: false
           })
         }
       },
       fail: function (res) {
         console.log("fail:" + res);
       },
     })}*/
  /* 
  var service = 'ReceiptAddress.get';
  console.log("openId:" + openId);
  wx.request({
    method: 'POST',
    url: app.globalData.APIURL,
    data: { service: service, openId: app.globalData.openId },
    header: { 'Content-Type': 'application/x-www-form-urlencoded' },
    success: function (res) {
      //console.log("success:" + res.data.data);
      if (!res.data.data.code) {
        var list = res.data.data.list;
        var addressId = '';
        for (var i in list) {
          if (list[i].isDefault) {
            addressId = list[i].addressId;
          }
        }
        that.setData({
          addressId: addressId
        })
      }
    },
    fail: function (res) {
      //console.log("fail:" + res);
    },
  }) 
  */

  getAddress: function () {
    var that = this;

    var openid = app.globalData.openId;
    app.util.request({
      'url': 'entry/wxapp/defaultaddress' + '&openid=' + openid,
      'cachetime': '30',
      success: function (res) {

        console.log("success:" + res.data.data);

        var aAddress = res.data.data;
        that.setData({
          aAddress: aAddress,
        })
        console.log(aAddress);
      },
      fail: function (res) {
        //console.log("fail:" + res);
      },
    })
  },
  changeAddress: function (e) {
    this.setData({ addressId: e.detail.value })
  },

  changeUserNote: function (e) {
    this.setData({ userNote: e.detail.value })
  },

  changeDeliveryType: function (e) {
    var that = this;
    var deliveryType = e.detail.value;
    var aDelivery = that.data.aDelivery;
    var deliveryFee = 0;
    for (var i in aDelivery) {
      if (aDelivery[i].type == deliveryType) {
        deliveryFee = aDelivery[i].fee;
        if (!deliveryFee) {
          deliveryFee = 0;
        }
      }
    }
    var payall = (parseFloat(that.data.paybase) + parseFloat(deliveryFee)).toFixed(2);
    that.setData({ deliveryType: deliveryType, deliveryFee: deliveryFee, payall: payall });

  },
  add: function (e) {
    var that = this;
    var openid = app.globalData.openId;

    var goodsid = e.target.dataset.id;
    console.log(that.data);
    var arraydetail = that.data.arraydetail;

    for (var i in arraydetail) {
      if (arraydetail[i].goodsid == goodsid) {
        arraydetail[i].total++;

        app.util.request({
          'url': 'entry/wxapp/Addcart&goodsid=' + goodsid + '&openid=' + openid,
          'cachetime': '30',
          success: function (res) {
            console.log(10);

          },
          fail: function (res) {
            console.log("fail:" + res);
          },

        })


      }
    }
    that.setData({ arraydetail: arraydetail });
    that.setinfo();
  },





  reduce: function (e) {
    console.log(" reduce");
    var that = this;
    var openid = app.globalData.openId;
    var goodsid = e.target.dataset.id;

    var arraydetail = that.data.arraydetail;
    for (var i in arraydetail) {
      if (arraydetail[i].goodsid == goodsid) {
        if (arraydetail[i].total > 1) {
          arraydetail[i].total--;
          app.util.request({
            'url': 'entry/wxapp/reduceCart&goodsid=' + goodsid + '&openid=' + openid,
            'cachetime': '30',
            success: function (res) {
              console.log(10);

            },
            fail: function (res) {
              console.log("fail:" + res);
            },

          })

          that.setData({ arraydetail: arraydetail });
        } else {
          that.del(goodsid);
        }
      }
    }

    that.setinfo();
  },
  del: function (goodsid) {
    var that = this;
    var openid = app.globalData.openId;

    //console.log("success:" + res.data.data.code);
    console.log(333333333);
    var myProduct = that.data.myProduct;
    var arraydetail = that.data.arraydetail;
    for (var i in arraydetail) {
      if (arraydetail[i].goodsid == goodsid)
        arraydetail.splice(i, 1);
    }
    for (var i in myProduct) {
      if (myProduct[i].goodsid == goodsid)
        myProduct.splice(i, 1);
    }
    app.util.request({
      'url': 'entry/wxapp/Delcart&goodsid=' + goodsid + '&openid=' + openid,
      'cachetime': '30',
      success: function (res) {
        console.log(10);

      },
      fail: function (res) {
        console.log("fail:" + res);
      },

    })
    that.setData({
      arraydetail: arraydetail,
      myProduct: myProduct,
    })
  },








  deleteselect: function (e) {
    var that = this;
    console.log(989)
    console.log(that);
    var myProduct1 = that.data.myProduct;
    var myProduct = that.data.myProduct;
    console.log(myProduct1);
    for (var i in myProduct) {
      if (myProduct[i] == i)
        that.del(i);
    }
  },
  selectProduct: function (e) {
    var that = this;
    var productId = e.target.dataset.id;
    var arraydetail = that.data.arraydetail;

    var myProduct = that.data.myProduct;
    for (var i in arraydetail) {
      if (arraydetail[i].goodsid == productId)
        myProduct[productId] = arraydetail[i];
    }
    console.log(77);
    console.log(that);
    console.log(88);
    console.log(myProduct);

    that.setData({ myProduct: myProduct });
    that.setinfo();

  },
  unselectProduct: function (e) {
    var that = this;
    var productId = e.target.dataset.id;
    var myProduct = that.data.myProduct;
    myProduct[productId] = false;
    that.setData({ myProduct: myProduct });
    that.setinfo();
    console.log(myProduct);
  },
  unselectall: function (e) {
    var that = this;
    var myProduct = [];
    var arraydetail = that.data.arraydetail;
    for (var i in arraydetail) {
      myProduct[arraydetail[i].productId] = false;
    }
    that.setData({ myProduct: myProduct, selectall: false });
    that.setinfo();
  },
  selectall: function (e) {
    var that = this;
    var myProduct = [];
    var arraydetail = that.data.arraydetail;
    for (var i in arraydetail) {
      myProduct[arraydetail[i].goodsid] = true;
    }
    that.setData({ myProduct: myProduct, selectall: true });
    that.setinfo();
  },
  buyproduct: function () {
    var that = this;
    var myProduct = that.data.myProduct;
    that.setData({ myProduct: myProduct });
    that.setinfo();
    that.getinfo();
  },

  onLoad: function (options) {

    var that = this;
    if (options.fromInviteCode) {
      app.globalData.fromInviteCode = options.fromInviteCode;
    }
    app.appstart();
    that.setData({ buttonconfirm: true, buttonbuy: false });


    wx.getSystemInfo({
      success: function (res) {

        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });

    that.getlist();
    that.getAddress();
  },


})